package lucene.server.common.dbmeta;

import lucene.server.common.utils.DatabaseUtil;
import lucene.server.common.utils.TypeUtil;
import java.sql.*;
import java.util.*;

/**
 * @author jinji
 */
public class DBMetaUtil {


    public static List<String> getGetAllTables(DatabaseMetaData metaData) throws SQLException {
        ResultSet resultSet = metaData.getTables(null, null, null, null);
        List<String> tables = new ArrayList<>();
        while (resultSet.next()) {
            tables.add(resultSet.getString("TABLE_CAT") + "::" + resultSet.getString("TABLE_NAME"));
        }
        DatabaseUtil.close(resultSet);
        return tables;
    }
    public static List<ColumnMeta> getTableColumns(DatabaseMetaData metaData,String databaseName,String tableName) throws SQLException {
        ResultSet resultSet = metaData.getColumns(databaseName, databaseName, tableName, null);
        List<ColumnMeta> columns = new ArrayList<>();
        while (resultSet.next()) {
            ColumnMeta columnMeta = new ColumnMeta();
            columnMeta.setTableCat(databaseName);
            columnMeta.setTableName(tableName);
            columnMeta.setDataType(resultSet.getInt("DATA_TYPE"));
            columnMeta.setTypeName(TypeUtil.SQLTypeToJavaType(resultSet.getInt("DATA_TYPE")).getSimpleName());
            columnMeta.setColumnName(resultSet.getString("COLUMN_NAME"));
            columnMeta.setColumnIndex( resultSet.getInt("ORDINAL_POSITION")-1);
            columnMeta.setOriginalType(resultSet.getString("TYPE_NAME"));
            columnMeta.setColumnRemark(resultSet.getString("REMARKS"));
            columnMeta.setColumnSize(resultSet.getString("COLUMN_SIZE"));
            columnMeta.isBinaryType = TypeUtil.isBinaryColumn(resultSet.getInt("DATA_TYPE")) ;
            columnMeta.isStringType = TypeUtil.isStringColumn(resultSet.getInt("DATA_TYPE"));
            columnMeta.isDateTimeType = TypeUtil.isDatetimeColumn(resultSet.getString("TYPE_NAME"));
            columns.add(columnMeta);
        }
        DatabaseUtil.close(resultSet);
        return columns;
    }

}
